/**
 * Description:
 * Class Name:RowSetFactoryTest
 * Date:2022/4/10 13:20
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_6_使用RowSet1_1来包装结果集._13_6_1_RowSetFactory与RowSet;

import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import java.io.FileReader;
import java.util.Properties;

public class RowSetFactoryTest {
    private String driver;
    private String url;
    private String user;
    private String pwd;

    public void initParam(String paramFilePath) throws Exception{
        Properties props = new Properties();
        props.load(new FileReader(paramFilePath));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }

    public void update(String sql) throws Exception{
        RowSetFactory factory = RowSetProvider.newFactory();    // RowSetFactory没实现AutoClosable接口
        try (
                JdbcRowSet jdbcRs = factory.createJdbcRowSet()
                ){
            // 设置必要的连接信息
            jdbcRs.setUrl(url);
            jdbcRs.setUsername(user);
            jdbcRs.setPassword(pwd);
            // 设置SQL查询语句
            jdbcRs.setCommand(sql);
            // 执行查询
            jdbcRs.execute();

            // 将记录指针放到最后之后，然后指针往前进一行开始循环
            jdbcRs.afterLast();
            while (jdbcRs.previous()){
                System.out.println("打印第" + jdbcRs.getRow() + "行记录：" + jdbcRs.getString(1) + "\t"
                + jdbcRs.getString(2) + "\t"
                + jdbcRs.getString(3));
                if (jdbcRs.getInt("student_id") == 3){
                    // 修改指定的记录
                    jdbcRs.updateString("student_name", "孙悟空_by_CH13_RowSet");
                    // 提交修改
                    jdbcRs.updateRow();
                }
            }
        }
    }

    public static void main(String[] args) throws Exception{
        var rft = new RowSetFactoryTest();
        rft.initParam("Chapter_13_mysql.ini");
        Class.forName(rft.driver);

        rft.update("select * from student_table");
    }
}
